/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.model.command;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Namespace;
import org.eclipse.uml2.uml.Type;

/**
 * Command to find a type with a given name.
 * 
 * <p>
 * The following attributes must be set for the command to complete
 * successfully:
 * </p>
 * <ul>
 * <li>Context
 * <li>Name
 * </ul>
 * 
 * <p>
 * The following attributes can be read to access the result of the command:
 * </p>
 * <ul>
 * <li>Type - will be null if not found.
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class FindTypeCommand extends Command {

	private Namespace context;
	private String name;
	private Type type;

	public FindTypeCommand() {
	}

	public FindTypeCommand(final Namespace context, final String name) {
		setContext(context);
		setName(name);
	}

	public void setContext(final Namespace context) {
		this.context = context;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public Type getType() {
		return type;
	}

	@Override
	public void execute() {
		if (name == null || name.trim().length() == 0)
			return; // nothing to do, keep result == null

		Namespace searchContext = context;
		while (searchContext != null) {
			for (Object o : searchContext.getOwnedMembers()) {
				if (o instanceof Type) {
					Type candidate = (Type) o;
					if (name.equalsIgnoreCase(candidate.getName())) {
						type = candidate;
						return;
					}
				}
			}
			searchContext = (Namespace) searchContext.getOwner();
		}
	}

	@Override
	public void undo() {
		type = null;
	}

	@Override
	public void redo() {
		this.execute();
	}

	@Override
	public void dispose() {
		context = null;
		name = null;
		type = null;
	}
}
